<?php

/*
* Manages data for all pages. 
* @author    René Giller
* @version   1.0
* @date      10.02.2009
*/
class Model {
    protected $data;            // contains all elements to be displayed on the page
    protected $dico;            // contains all texts in the correct language of the current page
    public $currentPage;     // the page currently visited
    protected $promo = true;    // indicates if there is a promotion right now
    protected $success;         // success message
    public $brand;
    
    private static $instance;


    /**
    * Singleton : private constructor
    * Stores the current page
    */
    protected function __construct() {
        global $currentPage, $brand;
        $this->currentPage = $currentPage;
        $this->brand = $brand;
    }

    /**
    * Singleton : instance getter
    * @return       the unique instance of the class
    */
    public static function getInstance() {
        if (empty(self::$instance))
            self::$instance = new Model_user();
        return self::$instance;
    }

    /**
    * gets translated textes for the current page from DB
    * @param lang   String      current language
    */
    public function translate($lang) {
        $query = new Query(SELECT, 'dico', array('label', 'text'));
        $query->filter('page', $this->currentPage, AND_OP, EQ, PAR_OPEN);
        $query->filter('page', 'all', OR_OP, EQ, PAR_CLOSE);
        $query->filter('lang', $lang, AND_OP);
        $this->dico = $query->execute('text', 'label');
    }

    /**
    * retrieves translated text for current page
    * @param    label   String      label to be replaced by text in correct language
    * @return           String      text to be printed or label if no translation is provided
    */
    public function getLabel($label) {
        if (isset($this->dico[$label]))
            return $this->dico[$label];
        else
            return $label."_!!";
    }

    /**
    * gets the menu
    * @return     array      the menu
    */
    public function getMenu() {
        return $this->menu;
    }

    /**
    * gets the menu
    * @return     array      the menu
    */
    public function getSubMenu() {
        $topMenu = Helper::array_search_recursive($this->currentPage, $this->menu);
            
        if (!$topMenu)
            //$topMenu = array_search(PAGE, $this->menu);
            return $this->menu['home'];

        return $this->menu[$topMenu];
        /*
        foreach ($array as $key => $value) {
            if (isarray($value))
                $topMenu = getTopMenu();
            
        }
        $topMenu = array_search($this->currentPage, $this->menu);
        if (!$topMenu)
            return PAGE;
            
        return $topMenu;*/
    }

    /**
    * gets the menu's second level of the selected first level
    * @return     array      the menu's second level
    */
    public function getSubMenu2() {            
        if ($page = array_search($this->currentPage, $this->menu))
            return $this->menu[$page];
        
        return array('error'); //current page doesn't exists
    }

    /**
    * gets the item's names to be printed
    * @return     array[String]      the item's names
    */
    public function getContent() {
        return array_keys($this->data);
    }

    /**
    * Gets asked ressource asociated to the current page
    * @param ressource  String   ressource name to retreive
    * @return           mixed    asked ressource or null
    */
    public function get($ressource) {
        if (array_key_exists($ressource, $this->data))
            return $this->data[$ressource];
        else
            return null;
    }

    /**
    * Gets all images' name and url within the given directory
    * @param directory  String          directory where images are stored
    * @return           array[String]   array of images' names
    */
    protected static function getImages($directory, $link = true) {
        if ($dir = opendir($directory)) {
            while (($file = readdir($dir)) !== false)
                if ($file != '.' && $file != '..' && $file != 'thumbs' && $file != '.svn' && $file != 'texts.txt')
                    if ($link)
                        $images[$directory.$file] = $directory.'thumbs/'.$file;
                    else
                        $images[substr($file, 0, -4)] = $directory.$file;
            closedir($dir);
        }
        
        if (isset($images))
            return $images;
        else
            return null;
    }

    /**
    * Gets one random image from given array
    * @param directory  array[String => String]     all images in the form url => imageName
    * @return           array[String => String]     array containing only selected image or null
    */
    protected static function getRandomImage($images) {
        if (empty($images))
            return null;
            
        return $images[array_rand($images)];
    }

    /**
    * Gets the paragraphs to be printed on this page
    * @return   array[String => String]      label and title of the paragraphs to be printed or null
    */
    protected function getParags() {
        $i = 1;
        while (array_key_exists('parag'.$i, $this->dico))
            if (array_key_exists('paragTitle'.$i, $this->dico))
                $texts['parag'.$i] = 'paragTitle'.$i++;
            else
                $texts['parag'.$i++] = '';

        if (isset($texts))
            return $texts;
        else
            return null;
    }

    /**
    * Gets the paragraphs to be printed on this page
    * @return   array[String => String]      label and title of the paragraphs to be printed or null
    */
    protected function getParagsWithImages($directory) {
        $i = 1;
        $parag = array();
        $images = self::getImages($directory, false);
        if (!is_null($images)) {
            $path = array_values($images);
            $images = array_keys($images);
        }
        while (array_key_exists('parag'.$i, $this->dico)) {
            if (array_key_exists('paragTitle'.$i, $this->dico))
                $parag[$i]['title'] = 'paragTitle'.$i;
            $parag[$i]['text'] = 'parag'.$i;
            if (!is_null($images)) {
                $parag[$i]['image'] = $images[$i-1];
                $parag[$i]['path'] = $path[$i-1];
            } else {
                $parag[$i]['image'] = null;
                $parag[$i]['path'] = null;
            }
            $i++;
        }
        if (isset($parag))
            return $parag;
        else
            return null;
    }

    /**
    * Gets all images' name and url strored into the DB and to be printed on this page
    * @param directory  String          directory where images are stored
    * @return           array[String]   array of images' names or null
    */
    protected function getImagesDB($directory) {
        $query = new Query(SELECT, 'products', array('logo', 'text'));
        $query->filter('page', $this->currentPage);
        $query->orderBy('order');
        $images = $query->execute();
        
        if (!isset($images))
            return null;
        foreach ($images as $key => $product)
            $images[$key]->logo = $directory.$images[$key]->logo;            
        return $images;
    }

    /**
    * Gets all images' name and url strored into the DB and to be printed on this page
    * @param directory  String          directory where images are stored
    * @return           array[String]   array of images' names or null
    */
    protected function getProductsDB($directory, $brand = null) {
        $query = new Query(SELECT, 'products', array('image', 'brand', 'name', 'text', 'price_new', 'price'));
        if (!is_null($brand))
            $query->filter('brand', $brand);
        $query->filter('page', $this->currentPage);
        $query->orderBy('order');
        $product = $query->execute();

        if (!isset($product))
            return null;
        foreach ($product as $key => $article)
            $product[$key]->image = $directory.$product[$key]->image;
        return $product;
    }
    
    /**
    * Checks if there is a pormotion currently
    * @return       Boolean      true if there is a promotion, false otherwise
    */
    public function hasPromo() {
        return $this->promo;
    }

    /**
    * Checks if given label is to be translated
    * @param label  String       label to be tested
    * @return       Boolean      true if label exists, false otherwise
    */
    public function isLabel($label) {
        return array_key_exists($label, $this->dico);
    }
    
    /**
    * Gets success message assciated to this page
    * @return       String      the message
    */
    public function getSuccessMsg() {
        return $this->success;
    }

// form data
    /**
    * Gets the form's field's names
    * @return       array[String]      field's names
    */
    public function getForm() {
        if (array_key_exists('form', $this->data))
            return array_keys($this->data['form']);
        else
            return null;
    }
    
    /**
    * Gets the field's associated type
    * @param    field   String      field's name to retrieve type
    * @return           String      the given field's type
    */
    public function getFieldType($field) {
        return $this->data['form'][$field]['type'];
    }

    /**
    * Gets the field's associated value
    * @param field  String      field's name to be retrieve the value
    * @return       String      the value associated to the given field
    */
    public function getFieldValue($field) {
        return $this->data['form'][$field]['value'];
    }

    /**
    * Sets the value of given field
    * @param key    String      field's name of whom to set the value
    * @param value  String      value to accosiate to given key
    */
    public function setFieldValue($key, $value) {
        $this->data['form'][$key]['value'] = $value;
    }

    /**
    * Indicates if the given field is required
    * @param field  String      field's name to be tested
    * @return       Boolean     "true" if the field is required, "false" otherwise
    */
    public function isRequired($field) {
        return $this->data['form'][$field]['required'];
    }

    /**
    * Indicates if the given field has an imposed format
    * @param field  String      field's name to be tested
    * @return       Boolean     "true" if the field has an associated format, "false" otherwise
    */
    public function hasFormat($field) {
        return !empty($this->data['form'][$field]['format']);
    }

    /**
    * Gets the field's associated format
    * @param field  String     field's name to be tested
    * @return       String     the field's associated format
    */
    public function getFieldFormat($field) {
        return $this->getLabel($this->data['form'][$field]['format']);
    }

    /**
    * Gets the field's associated response type
    * @param field  String     field's name to be tested
    * @return       String     the field's associated response type
    */
    public function getResponseType($field) {
        return $this->data['form'][$field]['responseType'];
    }
    
    public function getLinks($text) {
        global $model;
        
        return str_replace($model->textLinks1, $model->textLinks2, $text);  
    }
    
    public function readFile($filename) {
        $lines = array();
        
        $handle = @fopen($filename, "r");
        if ($handle) {
            while (!feof($handle)) {
                $buffer = fgets($handle, 100);
                $array = explode(':', $buffer);
                $lines['images/realizations/sono/'.$array[0]] = $array[1];
            }
            fclose($handle);
        }
        return $lines;
    }
}